﻿/* Copyright (c) 2010 Lexalytics Inc.

 Permission is hereby granted, free of charge, to any person
 obtaining a copy of this software and associated documentation
 files (the "Software"), to deal in the Software without
 restriction, including without limitation the rights to use,
 copy, modify, merge, publish, distribute, sublicense, and/or sell
 copies of the Software, and to permit persons to whom the
 Software is furnished to do so, subject to the following
 conditions:

 The above copyright notice and this permission notice shall be
 included in all copies or substantial portions of the Software.

 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
 OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
 NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
 HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
 WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
 OTHER DEALINGS IN THE SOFTWARE.
*/

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

// Needed for Office and Excel integration
using Excel = Microsoft.Office.Interop.Excel;

namespace Lexalytics4Excel.Dialogs
{
    /// <summary>
    /// Dialog allowing user to select metadata column to sort results based on 
    /// unique values in selected column.
    /// </summary>
    public partial class SortDialog : Form
    {
        #region Member variables
        private string wsName = "";
        private Excel.Range dataRange;
        private bool bIncludesHeader = false;
        private string strTextColumn = "1";
        private int nTextColumn = 1;
        private SortedList<int, string> lstColumns = new SortedList<int, string>();
        private Database.SqlHelper LocalDB = null;

        /// <summary>
        /// Identifier for column selected for filtering
        /// </summary>
        public string FilterColumn = "";

        /// <summary>
        /// List of unique values in selected column
        /// </summary>
        public List<string> ColumnValues = new List<string>();

        #endregion // Member variables

        /// <summary>
        /// Default constructor
        /// </summary>
        /// <param name="CurrentProject">Current data project for workbook</param>
        public SortDialog(DataProject CurrentProject)
        {
            try
            {
                wsName = CurrentProject.UserRangeWorksheet;
                Excel.Worksheet ws = (Excel.Worksheet)Globals.LexalyticsAddIn.Application.Worksheets[wsName];
                dataRange = ws.get_Range(CurrentProject.UserRangeSelection, Type.Missing);
                bIncludesHeader = CurrentProject.UserRangeIncludesHeader;
                strTextColumn = CurrentProject.UserRangeTextColumn;
                LocalDB = CurrentProject.LocalDatabase;
            }
            catch (Exception err)
            {
                Exception dlgErr = new Exception("An error occurred when displaying the Sort dialog.", err);
                throw dlgErr;
            }
            InitializeComponent();
        }

        #region Event handlers

        /// <summary>
        /// Form load event handler. Sets up user interface selections based on data range
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void SortDialog_Load(object sender, EventArgs e)
        {
            try
            {
                // Fill dropdown of filter column names
                string sColHeader = "";

                ColumnDropdown.Items.Clear();

                // Determine number of columns
                int nMinCol = 1;
                int nMaxCol = 1;
                string strRange_R1C1 = dataRange.get_Address(1, Type.Missing, Excel.XlReferenceStyle.xlR1C1, Type.Missing, Type.Missing);
                string[] arrBounds = strRange_R1C1.Split(new char[] { 'R', 'C', ':' }, StringSplitOptions.RemoveEmptyEntries);
                switch (arrBounds.GetLength(0))
                {
                    case 2:
                        nMinCol = Convert.ToInt32(arrBounds[0]);
                        nMaxCol = Convert.ToInt32(arrBounds[1]);
                        break;
                    case 4:
                        nMinCol = Convert.ToInt32(arrBounds[1]);
                        nMaxCol = Convert.ToInt32(arrBounds[3]);
                        break;
                    default:
                        nMaxCol = dataRange.SpecialCells(Excel.XlCellType.xlCellTypeLastCell, Type.Missing).Column;
                        break;
                }

                // Determine index of text column
                Excel.Worksheet ws = (Excel.Worksheet)Globals.LexalyticsAddIn.Application.Worksheets[wsName];
                Excel.Range _rng = ws.get_Range(String.Format("${0}$1:${0}$1", strTextColumn), Type.Missing);
                strRange_R1C1 = _rng.get_Address(1, 1, Excel.XlReferenceStyle.xlR1C1, Type.Missing, Type.Missing);
                arrBounds = strRange_R1C1.Split(new char[] { 'R', 'C', ':' }, StringSplitOptions.RemoveEmptyEntries);
                nTextColumn = Convert.ToInt32(arrBounds[1]);

                for (int nColIndex = nMinCol; nColIndex <= nMaxCol; nColIndex++)
                {
                    if (nColIndex != Convert.ToInt32(nTextColumn))
                    {
                        if (bIncludesHeader)
                        {
                            Excel.Range rHeader = (Excel.Range)dataRange.Cells[1, nColIndex];
                            if (rHeader.Value2 != null)
                                sColHeader = rHeader.Value2.ToString();
                            else
                                sColHeader = String.Format("Column{0}", nColIndex);
                        }
                        else
                        {
                            Excel.Range rHeader = (Excel.Range)dataRange.Cells[1, nColIndex];
                            sColHeader = String.Format("Column{0}", nColIndex);
                        }
                        lstColumns.Add(nColIndex, sColHeader);
                        ColumnDropdown.Items.Add(lstColumns[nColIndex]);
                    }
                }
                if (ColumnDropdown.Items.Count > 0)
                    ColumnDropdown.SelectedIndex = 0;
            }
            catch (Exception err)
            {
                MessageBox.Show("There was a problem determining sort options.\n" + err.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error, MessageBoxDefaultButton.Button1);
                OKButton.Enabled = false;
            }
        }

        /// <summary>
        /// Event handler for OK button. Sets dialog options and closes dialog
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void OKButton_Click(object sender, EventArgs e)
        {
            // Persist the name of the selected column
            FilterColumn = ColumnDropdown.SelectedItem.ToString();

            // Persist the unique values from the selected column
            string sColHeader = ColumnDropdown.SelectedItem.ToString();
            int nSelCol = 1;
            foreach (int nCol in lstColumns.Keys)
            {
                if (lstColumns[nCol].Equals(sColHeader))
                {
                    nSelCol = nCol;
                    break;
                }
            }

            // Fill value dropdown with unique items
            try
            {
                if (LocalDB != null)
                {
                    LocalDB.execute(String.Format("SELECT DISTINCT(value) FROM metadata WHERE label='{0}'", LocalDB.makeSafe(sColHeader)));
                    while (LocalDB.nextRow())
                    {
                        object[] oRow = LocalDB.getRow();
                        string strValue = oRow[0].ToString();
                        if (!ColumnValues.Contains(strValue))
                            ColumnValues.Add(strValue);
                    }
                }

            }
            catch (Exception err)
            {
                MessageBox.Show("There was a problem confirming your selection.\n" + err.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error, MessageBoxDefaultButton.Button1);
                OKButton.Enabled = false;
            }

            ColumnValues.Sort();
            this.Close();
        }

        /// <summary>
        /// Event handler for cancel button, clears dialog properties and closes dialog
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void CancelButton_Click(object sender, EventArgs e)
        {
            FilterColumn = "";
            ColumnValues.Clear();
            this.Close();
        }

        #endregion // Event handlers
    }
}
